package com.m3u8;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import com.m3u8.db.DbAction;
import com.m3u8.db.DbCallback;
import com.m3u8.db.DownloadM3u8DB;

/**
 * 数据库操作
 */
public class DataBaser implements Handler.Callback {

    private static DataBaser instance;
    private Handler mHandler;

    public static DataBaser getInstance() {
        if (instance == null) {
            synchronized (DataBaser.class) {
                if (instance == null) {
                    instance = new DataBaser();
                }
            }
        }
        return instance;
    }

    private DataBaser() {
        mHandler = new Handler(Downloader.getLooper(), this);
    }

    @Override
    public boolean handleMessage(Message msg) {
        return false;
    }

    public static void runDb(DbAction dbAction, DbCallback dbCallback) {
        DataBaser.getInstance().run(dbAction, dbCallback);
    }

    /**
     * @param dbAction
     */
    public static void runDb(DbAction dbAction) {
        DataBaser.getInstance().run(dbAction);
    }

    public static void runDb(DbAction dpAction, DbCallback... dbCallbacks) {
        DataBaser.getInstance().run(dpAction, dbCallbacks);
    }

    /**
     * 销毁消息
     */
    public static void release() {
        DataBaser.getInstance().releaseDB();
    }

    private void releaseDB() {
        mHandler.removeCallbacksAndMessages(null);
    }

    private void run(final DbAction dbAction, final DbCallback dbCallback) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                final Object o = dbAction.action();
                if (dbCallback != null) {
                    new Handler(Looper.getMainLooper()).post(new Runnable() { //回退到主线程
                        @Override
                        public void run() {
                            dbCallback.back(o);
                        }
                    });
                }
            }
        });
    }

    private void run(final DbAction dbAction, final DbCallback... dbCallbacks) {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                final Object o = dbAction.action();
                Object db = o;
                for (DbCallback dbCallback : dbCallbacks) {
                    db = dbCallback.back(db);
                }
            }
        });
    }
}
